package com.patui.Weibo;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class RequestHeader extends HttpHeaderFactory {
	public final static String TAG="@___Patui.RequestHeader";
	public final static String SPLITTER="___";
	
	//post的数据必须放在base string里面 ，利用生产的basestring生成signature
	@Override
	public WeiboParameters generateSignatureSort(WeiboParameters bundle) {
		if(bundle == null || bundle.size() == 0){
			return null;
		}
		List<String> strKeyList=bundle.sortAll(bundle);
		WeiboParameters pp = new WeiboParameters();
		for(int mi=0;mi<strKeyList.size();mi++)
		{
			String key=strKeyList.get(mi);
			pp.add(key, bundle.getValue(key));
		}
        return pp;
	}

	@Override
	public String generateSignature(String data, Token token) throws WeiboException {
		byte[] byteHMAC = null;
        try {
            Mac mac = Mac.getInstance(HttpHeaderFactory.CONST_HMAC_SHA1);
            SecretKeySpec spec = null;
            if (null == token.getSecretKeySpec()) 
            {
            	String oauthSignature = encode(Weibo.APP_SECRET) + "&" + encode(token.getSecret());
                spec = new SecretKeySpec(oauthSignature.getBytes(), HttpHeaderFactory.CONST_HMAC_SHA1);
                token.setSecretKeySpec(spec);
            }
            spec = token.getSecretKeySpec();
            mac.init(spec);
            byteHMAC = mac.doFinal(data.getBytes());
        } catch (InvalidKeyException e) {
            throw new WeiboException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new WeiboException(e);
        }
        return String.valueOf(Utility.base64Encode(byteHMAC));
	}

	@Override
	public void addAdditionalParams(WeiboParameters des, WeiboParameters src) {
		// TODO Auto-generated method stub
		
	}

}
